/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.pa165.web;

import cz.muni.fi.pa165.portalnahouby.api.dto.ForestDTO;
import cz.muni.fi.pa165.portalnahouby.api.dto.MushroomDTO;
import cz.muni.fi.pa165.portalnahouby.api.serviceinterface.ForestService;
import cz.muni.fi.pa165.portalnahouby.api.serviceinterface.MushroomService;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrors;
import org.apache.commons.beanutils.BeanToPropertyValueTransformer;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.orm.jpa.JpaSystemException;

/**
 *
 * @author ceja
 */
@UrlBinding("/forests/{$event}/{forest.id}")
public class ForestsActionBean implements ActionBean {

    private ActionBeanContext context;
    @SpringBean
    private ForestService forestManager;
    @SpringBean
    private MushroomService mushroomManager;

    @DefaultHandler
    public Resolution all() {
        return new ForwardResolution("/forest.jsp");
    }

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }

    public List<ForestDTO> getForests() {
        return forestManager.getAllForests();
    }

    public List<MushroomDTO> getMushrooms() {
        return mushroomManager.getListSortByName();
    }

    @Before(stages = LifecycleStage.BindingAndValidation, on = {"edit", "save"})
    public void loadForestFromDatabase() {
        String ids = context.getRequest().getParameter("forest.id");
        if (ids == null) {
            return;
        }
        forest = forestManager.findForest(Long.parseLong(ids));
    }
    @ValidateNestedProperties(value = {
        @Validate(on = {"add", "save"}, field = "name", required = true, maxlength = 255),
        @Validate(on = {"add", "save"}, field = "info", maxlength = 255)
    })
    private ForestDTO forest;

    
    public Resolution add() {
        String[] ids = context.getRequest().getParameterValues("mushroomsIds");
        List<MushroomDTO> mushrooms = new LinkedList<MushroomDTO>();
        if (ids != null) {

            for (String idsMushroom : ids) {
                mushrooms.add(mushroomManager.findMushroom(Long.parseLong(idsMushroom)));
            }

            this.forest.setMushrooms(mushrooms);
        }

        try {
            forestManager.addForest(forest);

        } catch (JpaSystemException jse) {
            ValidationErrors errors = new ValidationErrors();
            errors.add("name", new LocalizableError("forest.duplicity"));
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution(this.getClass(), "all");
    }

    
    public Resolution save() {
        String[] ids = context.getRequest().getParameterValues("mushroomsIds");
        List<MushroomDTO> mushrooms = new LinkedList<MushroomDTO>();
        if (ids != null) {

            for (String idsMushroom : ids) {
                mushrooms.add(mushroomManager.findMushroom(Long.parseLong(idsMushroom)));
            }

            this.forest.setMushrooms(mushrooms);
        }

        try {
            forestManager.editForest(forest);

        } catch (JpaSystemException jse) {
            ValidationErrors errors = new ValidationErrors();
            errors.add("name", new LocalizableError("forest.duplicity"));
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution(this.getClass(), "all");
    }

    public ForestDTO getForest() {
        return forest;
    }

    public void setForest(ForestDTO forest) {
        this.forest = forest;
    }

    
    public Resolution edit() {
        return new ForwardResolution("/forestedit.jsp");
    }

    
    public Resolution delete() {

        try {
            forestManager.deleteForest(forest.getId());

        } catch (JpaSystemException jse) {
            ValidationErrors errors = new ValidationErrors();
            errors.add("name", new LocalizableError("forest.hasVisit"));
            getContext().setValidationErrors(errors);
            return getContext().getSourcePageResolution();
        }
        return new RedirectResolution(this.getClass(), "all");

    }
    
	public List<Long> getMushroomsIds() {
        if (forest != null) {
            List<MushroomDTO> test = forest.getMushrooms();
            if (!test.isEmpty()) {
                return (List<Long>) CollectionUtils.collect(forest.getMushrooms(),
                        new BeanToPropertyValueTransformer("id"));
	}
	}
        return new ArrayList<Long>();
}
}
